package com.fpost.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.fpost.dao.GenericDAO;
import com.fpost.domain.ArticleType;

public class ArticleTypeDAO extends GenericDAO<ArticleType> {
	
	@Override
	public Long save(ArticleType articleType) throws HibernateException {
		Long articleTypeId = null;
		Session session = getSessionFactory().openSession();
		try {
			session.beginTransaction();
			articleTypeId = (Long) session.save(articleType);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			throw e;
		} finally {
			session.close();
		}
		return articleTypeId;
	}

	@Override
	public void delete(long id) throws HibernateException {
		Session session = getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.delete(get(id));
			session.getTransaction().commit();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			throw e;
		} finally {
			session.close();
		}

	}

	@Override
	public void delete(ArticleType articleType) throws HibernateException {
		Session session = getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.delete(articleType);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			throw e;
		} finally {
			session.close();
		}

	}

	@Override
	public ArticleType get(long id) throws HibernateException {
		Session session = getSessionFactory().openSession();
		ArticleType articleType = null;
		try {
			session.beginTransaction();
			articleType = (ArticleType) session.get(ArticleType.class, id);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			throw e;
		} finally {
			session.close();
		}
		return articleType;
	}


	@Override
	public void saveOrUpdate(ArticleType articleType) throws HibernateException {
		Session session = getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.saveOrUpdate(articleType);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			throw e;
		} finally {
			session.close();
		}

	}
	
	public List<ArticleType> getAll() throws HibernateException {
		Session session = getSessionFactory().openSession();
		List<ArticleType> articleTypes;
		try {
			articleTypes = (List<ArticleType>) session.createCriteria(ArticleType.class).list();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw e;
		}
		return articleTypes;		
	}
}
